package xdu.lz.stage5_jucUtils.chapter6_forkjointask;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.LongStream;

/**
 * Created at 2019/10/20 0020 下午 3:08
 * <p>
 * abstract :ForkJoinTask
 * abstract      -->RecursiveTask 有返回值
 * abstract      -->RecursiveAction Void
 * 由ForkJoinPool调用管理
 */
public class ForkJoinRecursiveAction {

    /**
     * 无返回值
     */
    private static long MAX_SINGLE_COUNT = 500L;

    private static AtomicInteger sum = new AtomicInteger(0);

    //一般继承RecursiveTask或RecursiveAction实现compute方法，由ForkJoinPool调用submit传进去
    private static class CalculationAction extends RecursiveAction {

        private final long start;

        private final long end;

        private CalculationAction(long start, long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected void compute() {
            if (end - start <= MAX_SINGLE_COUNT) {
                sum.addAndGet((int) LongStream.rangeClosed(start, end).sum());
            } else {
                long mid = (start + end) >> 1;
                CalculationAction leftTask = new CalculationAction(start, mid);
                CalculationAction rightTask = new CalculationAction(mid + 1, end);
                leftTask.fork();
                rightTask.fork();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ForkJoinPool joinPool = new ForkJoinPool();
        //这里无返回值，返回的也是null
        ForkJoinTask<Void> future = joinPool.submit(new CalculationAction(1, 2000));
        joinPool.awaitTermination(1,TimeUnit.SECONDS);
        System.out.println("future.get == null ? " + (future.get() == null));
        System.out.println(sum.get());
    }
}
